﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace MetroManagement
{
    /// <summary>
    /// 地铁公告应用服务类
    /// </summary>
    public class NoticeAppService : ApplicationService, INoticeAppService
    {
        private readonly IRepository<Notice, int> _noticeRepository;

        public NoticeAppService(
            IRepository<Notice, int> noticeRepository)
        {
            _noticeRepository = noticeRepository;
        }

        // 分页列表
        public async Task<ListResponse<NoticeDto>> PagedListAsync(
            PagedListRequest request, string title)
        {
            // 查询
            var query = _noticeRepository
                .WhereIf(!string.IsNullOrWhiteSpace(title), m => m.Title.Contains(title))
                .AsQueryable();
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Notice>, List<NoticeDto>>(list);
            return ListResponse<NoticeDto>.Successful(count, dtos);
        }

        // 获取
        public async Task<ResultResponse<NoticeDto>> GetAsync(int id)
        {
            var notice = await _noticeRepository.GetAsync(id);
            var dto = ObjectMapper.Map<Notice, NoticeDto>(notice);
            return ResultResponse<NoticeDto>.Successful(dto);
        }
    }
}